from xml.dom import minidom
import Book
import User

class Dao:
	
	def __init__(self, libraryFile='library.xml', userFile='user.xml'):
		""" default constructor """
		self._libraryFile = libraryFile
		self._userFile = userFile
		self._bookDictionary = {}
		self._userDictionary = {}
		self.readLibrary()
		self.readUser()
		
	def readLibrary(self):
		""" Read the library file put in _bookDictionary """
		self._library = minidom.parse(self._libraryFile)
	
	def getLibraryDoc(self):
		return self._library
		
	def getUserDoc(self):
		return self._user
		
	def getBookDictionary(self):		
		bookNodeList = self._library.getElementsByTagName('book')
		
		for bookNode in bookNodeList:
			self._bookId = bookNode.getElementsByTagName('bookid')[0].firstChild.data
			
			if bookNode.getElementsByTagName('category')[0]!='':
				book = Book.Book(bookId = self._bookId,
							 title = bookNode.getElementsByTagName('title')[0].firstChild.data,
							 author = bookNode.getElementsByTagName('author')[0].firstChild.data,
							 isbn = bookNode.getElementsByTagName('isbn')[0].firstChild.data,
							 category = bookNode.getElementsByTagName('category')[0].firstChild.data,
							 keyword = bookNode.getElementsByTagName('keyword')[0].firstChild.data,
							 available = bookNode.getElementsByTagName('available')[0].firstChild.data,
							 )
				
				
			self._bookDictionary[self._bookId] = book
		return self._bookDictionary
		
	def readUser(self):
		""" Read the User file put in _userDictionary """
		self._user = minidom.parse(self._userFile)
		
	def getUserDoc(self):
		return self._user
	
	#def getNextUserID(self):
	#	return int(self._user.getElementsByTagName('userid')[-1].firstChild.data) + 1

	def getNextBookID(self):
		return int(self._user.getElementsByTagName('bookid')[-1].firstChild.data) + 1
		
	def getUserDictionary(self):
		userNodeList = self._user.getElementsByTagName('user')
		
		for userNode in userNodeList:
			self._userId = userNode.getElementsByTagName('userid')[0].firstChild.data
			user = User.User(userId = self._userId,
							 username = userNode.getElementsByTagName('username')[0].firstChild.data,
							 email = userNode.getElementsByTagName('email')[0].firstChild.data,
							 bookList = self.handleUserBookList(userNode.getElementsByTagName('bookList')))
			self._userDictionary[self._userId] = user
		return self._userDictionary
	
	def getNextUserID(self):
		#return the next available UserID
		userNodeList = self._user.getElementsByTagName('user')
		lastUserID=userNodeList[0].getElementsByTagName('userid')[0].firstChild.data
		
		for userNode in userNodeList:
			thisUserID=userNode.getElementsByTagName('userid')[0].firstChild.data
			if lastUserID<thisUserID:
				lastUserID=thisUserID
		return str(int(lastUserID)+1)
	
	def updateBookStatus(self, bookid, status):
		toSet='false'
		if status.count("true")==1:
			toSet="false"
				
		#loop through bookid, to find target one
		top_element=self._library.documentElement
		childItr = top_element.firstChild
		done = False
		count=0
		while count < len(self._bookDictionary) : #keep doing until update is done
			if childItr.toxml().count('>' + bookid + '<')==1: #if the current child's name is 'bookid'
				childItr.lastChild.previousSibling.replaceChild(self._library.createTextNode(toSet),childItr.lastChild.previousSibling.firstChild)
						
				#print childItr.toxml() #print the child's availability
			childItr = childItr.nextSibling
			count=count+1 
				
		f=open('library.xml','w')
		self._library.writexml(f)
		f.close()
		
		self._bookDictionary[bookid].setAvailable(toSet)
		#self.readLibrary()
		#self.getBookDictionary()
	
	def addUserToDictionary(self,datalist):
			
		newUser=self._user.createElement('user')
		#userid element create
		userid=self._user.createElement('userid')
		newUserID=self._user.createTextNode(self.getNextUserID())
		userid.appendChild(newUserID)
		newUser.appendChild(userid)
		#username element create
		username=self._user.createElement('username')
		newUserName=self._user.createTextNode(datalist[0])
		username.appendChild(newUserName)
		newUser.appendChild(username)
		#email element create
		email=self._user.createElement('email')
		newUserEmail=self._user.createTextNode(datalist[1])
		email.appendChild(newUserEmail)
		newUser.appendChild(email)
		#booklist element create
		newUser.appendChild(self._user.createElement('booklist'))
		#add child
		
		#finished adding and checking, write XML data to file
		top_element=self._user.documentElement
		top_element.appendChild(newUser)
		
		f = open('user.xml', 'w')
		self._user.writexml(f)
		f.close()
		#Let's read over again
		self.readUser()
		self.getUserDictionary()
		return True
		
	def handleUserBookList(self, bookNodeList):
		bookList = []
		for bookNode in bookNodeList:			
			bookList.append(bookNode.getElementsByTagName('bookid')[0].firstChild.data)
			
		return bookList